package test.gdata.calendar;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class CalendarClient {
	// The base URL for a user's calendar metafeed (needs a username appended).
	private static final String METAFEED_URL_BASE = 
	      "https://www.google.com/calendar/feeds/";
	
	// The string to add to the user's metafeedUrl to access the event feed for
	// their primary calendar.
	private static final String EVENT_FEED_URL_SUFFIX = "/private/full";
	
	private CalendarService service;
	private String username;
	
	public CalendarClient(CalendarService service, String username, String password){
		this.service = service;
		this.username = username;
		if (username != null && password != null) {
		      try {
		        this.service.setUserCredentials(username, password);
		      } catch (AuthenticationException e) {
		        throw new IllegalArgumentException(
		            "Illegal username/password combination.");
		      }
		}
	}
	
	public List<CalendarEntry> getCalendarEntrys() throws IOException, ServiceException{
		// Send the request and receive the response:
		String feedHref = METAFEED_URL_BASE + "default/owncalendars/full";
		
	    CalendarFeed resultFeed = getFeed(feedHref, CalendarFeed.class);
	    return resultFeed.getEntries();
	}
	
	public List<CalendarEventEntry> getCalendarEventEntrys(CalendarEntry calendar) throws MalformedURLException, IOException, ServiceException{
		String feedHref = METAFEED_URL_BASE + username + EVENT_FEED_URL_SUFFIX;
		CalendarEventFeed feed = this.service.getFeed(new URL(feedHref), CalendarEventFeed.class);
		return feed.getEntries();
	}

	  /**
	   * Helper function to allow retrieval of a feed by string url, which will
	   * create the URL object for you.  Most of the Link objects have a string
	   * href which must be converted into a URL by hand, this does the conversion.
	   */
	  public <T extends CalendarFeed> T getFeed(String feedHref, Class<T> feedClass) throws IOException, ServiceException {
	    return service.getFeed(new URL(feedHref), feedClass);
	  }
}
